import { NextResponse } from 'next/server'
import prisma from '@/lib/db'
import { verifyToken } from '@/lib/auth'

// DELETE delete a copy
export async function DELETE(
  request: Request,
  { params }: { params: { id: string } }
): Promise<Response> {
  try {
    const token = request.headers.get('Authorization')?.split(' ')[1]
    const payload = token ? verifyToken(token) : null;
  
    if (!payload) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }
   
    const { id } = params
    // 先查询文案所属用户
    const copy = await prisma.productCopy.findUnique({
      where: { id }
    })
    
    if (!copy) {
      return NextResponse.json(
        { error: '未找到文案' },
        { status: 404 }
      )
    }

    
    // Then delete the copy itself
    await prisma.productCopy.delete({
      where: {
        id
      }
    })

    
    return NextResponse.json({ message: 'Copy deleted successfully' }, { status: 200 })
  } catch (error) {
    return NextResponse.json(
      { error: 'Failed to delete copy' },
      { status: 500 }
    )
  }
}

// GET get a single copy by ID
export async function GET(
  request: Request,
  { params }: { params: { id: string } }
): Promise<Response> {
  try {
    const { id } = params
    
    const copy = await prisma.productCopy.findUnique({
      where: {
        id
      }
    })
    
    if (!copy) {
      return NextResponse.json(
        { error: 'Copy not found' },
        { status: 404 }
      )
    }
    
    return NextResponse.json(copy, { status: 200 })
  } catch (error) {
    return NextResponse.json(
      { error: 'Failed to fetch copy' },
      { status: 500 }
    )
  }
}
